<?php
namespace easemob;

use think\Cache;
use think\Config;
use think\Exception;
use think\Log;

/**
 * 环信的im管理
 * @author fzf
 *
 */
class IM{
    const TOKEN_CACHE_KEY='im_accesstoken';
    
    public $apiurl='http://a1.easemob.com/';
    public $wrlog=true;
    
    private $config=[];
    
    function __construct($config=[]){
        $c=Config::get('im');
        if($c){
            $this->config=array_merge($c,$config);
            
        }        
        if(empty($this->config['orgname']) || empty($this->config['appname']) || empty($this->config['clientid']) || empty($this->config['clientsecret'])){
            throw new \Exception('配置项不完整',500);
        }
        
    }
    
    /**
     * 获取环信的token
     */
    public function getToken(){
        $cache=Cache::get(self::TOKEN_CACHE_KEY);
        if($cache){
            return $cache['access_token'];
        }else{
            $url=$this->geturl('token');
            $data=[
                "grant_type"=> "client_credentials",
                "client_id"=> $this->config['clientid'],
                "client_secret"=>$this->config['clientsecret'],
            ];
            
            $ret=$this->curl($url,$data);             
            if(isset($ret['access_token'])){
                Cache::set(self::TOKEN_CACHE_KEY,$ret,$ret['expires_in']-1800);
                return $ret['access_token'];
            }else{
                throw new \Exception('获取token失败',10000);
            }           
        }
        
        return false;
    }
    
    
   
    
    /**
     * 拼接url地址
     * @param unknown $name
     * @return string
     */
    protected  function geturl($name){
        return "{$this->apiurl}{$this->config['orgname']}/{$this->config['appname']}/{$name}";
    }
    
    protected function getAuthorization(){
        $token=$this->getToken();        
        return "Authorization:Bearer {$token}";
    }
    
    /**
     * 发送带header的post请求
     * @param unknown $url
     * @param unknown $data
     */
    protected function sentPost($url,$data){
        $header=[$this->getAuthorization(),'Content-type:application/json'];
        return $this->curl($url,$data,'post',$header);
    } 
    
    /**
     * 发送带token的get请求
     * @param unknown $url
     * @return boolean|mixed
     */
    protected function sentGet($url){
        $header=[$this->getAuthorization(),'Content-type:application/json'];
        return $this->curl($url,[],'get',$header);
    }
    
    /**
     * 发送带token的delete请求
     * @param unknown $url
     * @param unknown $data
     * @return boolean|mixed
     */
    protected function sentDelete($url){
        $header=[$this->getAuthorization(),'Content-type:application/json'];
        return $this->curl($url,[],'delete',$header);
        
    } 
    
    /**
     * 发送带token的put请求
     * @param unknown $url
     * @param unknown $data
     * @return boolean|mixed
     */
    protected function sentPut($url,$data){
        $header=[$this->getAuthorization(),'Content-type:application/json'];
        return $this->curl($url,$data,'put',$header);
        
    } 
    
    protected function sentUpload($url,$file){
        $data['file']=$file;
        $header=[$this->getAuthorization(),'Content-type: multipart/form-data','restrict-access:true'];
        return $this->curl($url,$data,'post',$header);
        
    }
    
    protected function curl($url,$data=[],$method='POST',$headers=[]){
        $curl=curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);       
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headers);
        
        $method=strtolower($method);
        if($method=='post'){
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
        }elseif($method=='delete'){
            curl_setopt ($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            //dump($curl);die;
        }elseif($method=='put'){
            curl_setopt ($curl, CURLOPT_CUSTOMREQUEST, "PUT");
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
        }       
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,true); 
        
        $output=curl_exec($curl);
        if (false===$output) {
            Log::write('curl: '.curl_error($curl));
            return false;
        }
        $httpCode = curl_getinfo($curl,CURLINFO_HTTP_CODE);
        curl_close($curl); 
        if($this->wrlog){
            Log::write($url.'->'.json_encode($headers).'->'.json_encode($data).'->'.$httpCode.' : '.$output);
        }
        if($ret=json_decode($output,true)){
            if(isset($ret['error'])){
                throw new \Exception($ret['error'],$httpCode);
            }else{
                return $ret;
            }
        }else{
            throw new \Exception('返回的不是josn格式的数据','10000');
        }
        
    }
}
